package com.secure.orm.controller.billPay;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.secure.orm.controller.BaseController;
import com.secure.orm.model.PayOrder;
import com.secure.orm.model.response.ViewData;
import com.secure.orm.service.billPay.BillPayService;

@Controller
@RequestMapping("/BillPay")
public class BillPayController extends BaseController {
	@Autowired
	private BillPayService billPayService;

	@RequestMapping("PayEntry")
	public String PayEntry(PayOrder payOrder, BindingResult result, HttpServletRequest request, Model model) {
		if (result.hasErrors()) {
			DefaultMessageSourceResolvable objError = result.getAllErrors().get(0);
            model.addAttribute("message",objError.getDefaultMessage());
    		return "BillPay/error";
		}
		if (StringUtils.isEmpty(payOrder.getOrderId())){
			model.addAttribute("message","订单号不能为空");
            return "BillPay/error";
		}
		if (StringUtils.isEmpty(payOrder.getUserId())){
			model.addAttribute("message","用户ID不能为空");
            return "BillPay/error";
		}
		if (payOrder.getOrderAmount()<=0){
			model.addAttribute("message","商品金额不能少于0");
            return "BillPay/error";
		}
		if (StringUtils.isEmpty(payOrder.getToken())){
			model.addAttribute("message","签名不能为空");
            return "BillPay/error";
		}
		
		ViewData vd = billPayService.entryPay(payOrder);
		if (vd.getCode() != 0) {
			model.addAttribute("message",vd.getResult());
			return "BillPay/error";
		}
		model.addAttribute("payOrder", payOrder);
		return "BillPay/PayEntry";
	}
	
	@RequestMapping(value="/PayProcess",method = RequestMethod.POST)
	public String PayProcess(PayOrder payOrder, BindingResult result,Model model){
		if (result.hasErrors()){  
			DefaultMessageSourceResolvable objError = result.getAllErrors().get(0);
            model.addAttribute("message",objError.getDefaultMessage());
            return "BillPay/error";
		}
		ViewData vd = billPayService.processPay(payOrder);
		if (vd.getCode() != 0) {
			model.addAttribute("message",vd.getResult());
			return "BillPay/error";
		}
		model.addAttribute("requestForm",vd.getResult());
		return "BillPay/payRedirect";
	}

}
